<template>
  <div class="chat-container">
    <!-- 顶部标题栏 -->
    <div class="chat-header">
      <h1>智能角色对话</h1>
    </div>

    <!-- 角色选择区域 -->
    <div class="role-selector">
      <van-radio-group v-model="selectedRole" direction="horizontal" @change="onRoleChange">
        <van-radio
            v-for="role in defaultRoles"
            :key="role.value"
            :name="role.value"
            class="role-item"
        >
          <span class="role-icon">{{ role.icon }}</span>
          <span class="role-name">{{ role.label }}</span>
        </van-radio>
        <van-radio name="custom" class="role-item">
          <span class="role-icon">✏️</span>
          <span class="role-name">自定义</span>
        </van-radio>
      </van-radio-group>
    </div>

    <!-- 自定义角色输入 -->
    <div
        v-if="selectedRole === 'custom'"
        class="custom-role-form"
        :class="{ 'slide-in': showCustomForm }"
    >
      <van-field
          v-model="customRoleName"
          placeholder="请输入角色名称"
          clearable
          label="角色名称"
      />
      <van-field
          v-model="customRoleDesc"
          placeholder="请输入角色描述"
          clearable
          label="角色描述"
          type="textarea"
          rows="2"
      />
      <van-button
          size="small"
          type="primary"
          @click="saveCustomRole"
          round
      >
        保存角色
      </van-button>
    </div>

    <!-- 聊天消息区域 -->
    <div ref="messagesContainer" class="chat-messages">
      <!-- 日期分割线 -->
      <div class="date-divider" v-if="messages.length > 0">
        {{ today }}
      </div>

      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message', msg.role, 'message-fade-in']"
      >
        <div class="avatar">
          <span>{{ msg.role === 'user' ? '👤' : getRoleAvatar(msg.role) }}</span>
        </div>
        <div class="message-content">{{ msg.content }}</div>
      </div>

      <div v-if="isLoading" class="message assistant message-fade-in">
        <div class="avatar">
          <span>{{ getRoleAvatar(currentRole.name) }}</span>
        </div>
        <div class="message-content">
          {{ partialResponse }}<span class="cursor">|</span>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <van-field
          v-model="inputMessage"
          :disabled="isLoading"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
          clearable
          class="message-input"
          :autosize="{ minRows: 1, maxRows: 4 }"
          type="textarea"
      />
      <van-button
          :disabled="!inputMessage.trim()"
          :loading="isLoading"
          type="primary"
          @click="sendMessage"
          round
          icon="send"
          class="send-btn"
      />
    </div>
  </div>
</template>

<script setup>
import {computed, nextTick, onUnmounted, ref, watch} from 'vue'
import {showFailToast, showToast} from 'vant'
import {_axios} from '../api/index.js'

// 响应式数据
const selectedRole = ref('医生')
const customRoleName = ref('')
const customRoleDesc = ref('')
const inputMessage = ref('')
const messages = ref([])
const isLoading = ref(false)
const partialResponse = ref('')
const abortController = ref(null)
const messagesContainer = ref(null)
const showCustomForm = ref(false)

// 默认角色配置（带图标）
const defaultRoles = [
  { value: '医生', label: '医生', icon: '👨⚕️' },
  { value: '厨师', label: '厨师', icon: '👨🍳' },
  { value: '老师', label: '老师', icon: '👨🏫' },
  { value: '律师', label: '律师', icon: '⚖️' },
  { value: '女朋友', label: '女朋友', icon: '💑' },
  { value: '狗', label: '狗', icon: '🐶' }
]

// 欢迎消息映射
const welcomeMessages = {
  '医生': '你好！我是一名专业医生，有什么健康问题可以问我。请注意，线上咨询不能替代面诊，严重情况请及时就医。',
  '老师': '你好呀！我是你的老师，有什么学习上的问题或者想了解的知识，都可以跟我说哦。',
  '厨师': '你好！我是一名厨师，无论是想学习新菜式，还是需要食材搭配建议，都可以问我。',
  '律师': '你好，我是律师。如果你有法律相关问题，可以向我咨询。',
  '女朋友': '亲爱的，终于等到你啦！今天过得怎么样呀？有什么想跟我说的吗~',
  '狗': '汪汪！(摇尾巴) 主人你好呀！想和我一起玩吗？'
}

// 获取当前日期
const today = computed(() => {
  const date = new Date()
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
})

// 获取角色头像
const getRoleAvatar = (roleName) => {
  const role = defaultRoles.find(r => r.value === roleName)
  return role ? role.icon : '🤖'
}

// 监听消息变化，自动滚动到底部
watch(messages, async () => {
  await nextTick()
  scrollToBottom()
}, {deep: true})

// 监听部分响应变化，自动滚动到底部
watch(partialResponse, async () => {
  await nextTick()
  scrollToBottom()
})

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 角色变更处理
const onRoleChange = (name) => {
  // 清空聊天记录
  messages.value = []
  showCustomForm.value = name === 'custom'

  if (name !== 'custom') {
    // 添加欢迎消息
    messages.value.push({
      role: 'assistant',
      content: welcomeMessages[name] || '你好！很高兴为你服务。'
    })
  }
}

// 保存自定义角色
const saveCustomRole = () => {
  if (!customRoleName.value.trim() || !customRoleDesc.value.trim()) {
    showToast('请填写角色名称和描述')
    return
  }

  // 这里应该调用API保存自定义角色
  console.log('保存角色:', customRoleName.value, customRoleDesc.value)
  showToast('角色保存成功')

  // 清空聊天记录
  messages.value = []
  // 添加自定义角色欢迎消息
  messages.value.push({
    role: 'assistant',
    content: `你好！我是${customRoleName.value}，${customRoleDesc.value}`
  })
}

// 获取当前角色信息
const currentRole = computed(() => {
  if (selectedRole.value !== 'custom') {
    return {
      name: selectedRole.value,
      description: ''
    }
  }
  return {
    name: customRoleName.value,
    description: customRoleDesc.value
  }
})

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  // 添加用户消息到聊天记录
  messages.value.push({
    role: 'user',
    content: inputMessage.value
  })

  const question = inputMessage.value
  inputMessage.value = ''
  isLoading.value = true
  partialResponse.value = ''

  try {
    abortController.value = new AbortController()

    const response = await fetch(_axios.getUri() + '/ai/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('jwt'),
      },
      body: JSON.stringify({
        question,
        role: currentRole.value.name,
        roleDescription: currentRole.value.description
      }),
      signal: abortController.value.signal
    })

    if (!response.ok) {
      showFailToast(`HTTP error! status: ${response.status}`)
      return
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')

    while (true) {
      const {done, value} = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const data = line.substring(5).trim()
          if (data) {
            partialResponse.value += data
          }
        } else if (line.trim()) {
          partialResponse.value += line.trim()
        }
      }
    }

    // 流式输出完成，将完整响应添加到消息列表
    messages.value.push({
      role: 'assistant',
      content: partialResponse.value
    })

    partialResponse.value = ''
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('请求被取消')
      showToast('请求已取消')
    } else {
      console.log(error)
      showToast(error.message || '发送失败，请重试')
    }
  } finally {
    isLoading.value = false
    abortController.value = null
  }
}

// 组件卸载时取消请求
onUnmounted(() => {
  if (abortController.value) {
    abortController.value.abort()
  }
})

// 初始化欢迎消息
messages.value.push({
  role: 'assistant',
  content: welcomeMessages[selectedRole.value]
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
  padding: 0;
  overflow: hidden;
}

.chat-header {
  background: linear-gradient(135deg, #42b983 0%, #359469 100%);
  color: white;
  padding: 16px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chat-header h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.role-selector {
  padding: 12px 16px;
  background-color: white;
  overflow-x: auto;
  white-space: nowrap;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.role-item {
  display: inline-flex !important;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 20px;
  transition: all 0.2s ease;
}

.role-icon {
  font-size: 16px;
}

.role-name {
  font-size: 14px;
}

.custom-role-form {
  padding: 16px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin: 0 16px 16px;
  max-height: 0;
  opacity: 0;
  overflow: hidden;
  transition: all 0.3s ease;
}

.custom-role-form.slide-in {
  max-height: 300px;
  opacity: 1;
  margin-bottom: 16px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f7fa;
  background-image: linear-gradient(rgba(245, 247, 250, 0.8) 1px, transparent 1px),
  linear-gradient(90deg, rgba(245, 247, 250, 0.8) 1px, transparent 1px);
  background-size: 20px 20px;
}

.date-divider {
  text-align: center;
  margin: 10px 0 20px;
  color: #86909c;
  font-size: 12px;
  position: relative;
}

.date-divider::before,
.date-divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 40%;
  height: 1px;
  background-color: #e5e6eb;
}

.date-divider::before {
  left: 0;
}

.date-divider::after {
  right: 0;
}

.message {
  margin-bottom: 20px;
  display: flex;
  animation: fadeIn 0.3s ease forwards;
  opacity: 0;
  transform: translateY(10px);
}

.message-fade-in {
  animation: fadeIn 0.3s ease forwards;
}

@keyframes fadeIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message.assistant {
  justify-content: flex-start;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #e5e6eb;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  flex-shrink: 0;
}

.message.user .avatar {
  margin-right: 0;
  margin-left: 10px;
  background-color: #42b983;
  color: white;
}

.message-content {
  max-width: 75%;
  padding: 12px 16px;
  border-radius: 14px;
  word-break: break-word;
  line-height: 1.5;
  position: relative;
}

.message.user .message-content {
  background-color: #42b983;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.assistant .message-content {
  background-color: #ffffff;
  color: #303133;
  border: 1px solid #ebedf0;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.input-area {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  padding: 12px 16px;
  background-color: white;
  border-top: 1px solid #ebedf0;
}

.message-input {
  flex: 1;
  background-color: #f5f7fa !important;
  border-radius: 20px !important;
  padding: 8px 16px !important;
  min-height: 40px !important;
}

.message-input ::v-deep textarea {
  min-height: 24px !important;
  padding: 0 !important;
  border: none !important;
  resize: none !important;
}

.send-btn {
  width: 40px;
  height: 40px;
  border-radius: 50% !important;
  padding: 0 !important;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #42b983 !important;
  border-color: #42b983 !important;
  transition: all 0.2s ease !important;
}

.send-btn:active {
  transform: scale(0.95);
}

.cursor {
  animation: blink 1s infinite;
  font-weight: bold;
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

/* 滚动条美化 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.2);
}
</style>